﻿/*
 * (c) Stefan Bojarovski 2010
 * */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ASTBuilder
{
    class IfNode : NodesCollection, ITreeNode
    {
        private LexemeType lexType = LexemeType.IF_OPERATOR;
        private ITreeNode Condition; //Boolean expression or identifier
        private ITreeNode thenBranch; //Block
        private ITreeNode elseBranch; //Block

        public IfNode(ITreeNode boolExpr, ITreeNode firstBlock, ITreeNode secondBlock)
        {
            Condition = boolExpr;
            thenBranch = firstBlock;
            elseBranch = secondBlock;
        }
        public LexemeType getLexemeType()
        {
            return lexType;
        }
        public void printNode(String parentLevel, StreamWriter someStream)
        {
            someStream.WriteLine(parentLevel + " " + "If Operator:");
            someStream.WriteLine(parentLevel + " " + "Condition: ");
            Condition.printNode(parentLevel + " ", someStream);
            someStream.WriteLine(parentLevel + " " + "Then: ");
            thenBranch.printNode(parentLevel + " ", someStream);
            someStream.WriteLine(parentLevel + " " + "Else: ");
            elseBranch.printNode(parentLevel + " ", someStream);
        }
        public List<Command> evalNode(ref Direction next,
                                        ref Dictionary<String, Pair<IdentifierType, object>> Environment)
        {
            List<Command> ifres = new List<Command>();
            if (next != Direction.JUMP)
            {
                bool condition = (bool)Condition.evalNode(ref next, ref Environment)[0].getIdValue();
                if (condition)
                {
                    return thenBranch.evalNode(ref next, ref Environment);
                }
                else
                {
                    return elseBranch.evalNode(ref next, ref Environment);
                }
            }
            else
            {
                ifres.Add(new Command(CommandType.VOID, null, null));
                return ifres;
            }
        }
    }
}
